package com.hziee.mail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hziee.mail.model.SkuInfoEntity;
import com.hziee.mail.model.SkuInfoListEntity;
import com.hziee.mail.service.CartService;
import com.hziee.mail.util.FormatReturn;
import com.hziee.mail.util.RedisUtil;
import com.hziee.mail.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author ZX
 */
@RestController
@RequestMapping("/cart")
public class CartController extends FormatReturn {

    @Autowired
    private CartService cartService;


    @PostMapping("add_redis")
    public String addRedis(@RequestBody SkuInfoListEntity items, HttpServletResponse response) {
        for (int i = 0; i < items.getItems().size(); i++) {
            cartService.addRedis(items.getItems().get(i), items.getItems().get(i).getUserId());
        }
        RedisUtil redisUtil = (RedisUtil) SpringUtil.applicationContext.getBean("redisUtil");
        String cartValue = redisUtil.get(items.getItems().get(0).getUserId() + "cart");
        SkuInfoListEntity skuInfoListEntity = JSON.parseObject(cartValue, new TypeReference<SkuInfoListEntity>() {
        });
        return ajaxReturn(response, 1, "success", skuInfoListEntity);
    }

    @GetMapping("get_redis")
    public String getRedis(Integer userId, HttpServletResponse response) {
        System.out.println(userId);
        RedisUtil redisUtil = (RedisUtil) SpringUtil.applicationContext.getBean("redisUtil");
        String cartValue = redisUtil.get(userId + "cart");
        SkuInfoListEntity skuInfoListEntity = JSON.parseObject(cartValue, new TypeReference<SkuInfoListEntity>() {
        });
        return ajaxReturn(response, 1, "success", skuInfoListEntity);
    }

}
